﻿using AutoMapper;

using FluentValidation;

using Holla.Core.Application.ViewModels;
using Holla.Core.Domain.Entities;
using Holla.Core.Persistence;

using MediatR;

using System.Threading;
using System.Threading.Tasks;

namespace Holla.Core.Application.Commands
{
    public class TodoCreateCommand : IRequest<TodoViewModel>
    {
        public string Name { get; set; }
        public string Description { get; set; }

        public class Handler : IRequestHandler<TodoCreateCommand, TodoViewModel>
        {
            private readonly CoreDbContext _dbContext;
            private readonly IMapper _mapper;

            public Handler(CoreDbContext dbContext, IMapper mapper)
            {
                _dbContext = dbContext;
                _mapper = mapper;
            }

            public async Task<TodoViewModel> Handle(TodoCreateCommand request, CancellationToken cancellationToken = default)
            {
                var todo = new Todo
                {
                    Name = request.Name,
                    Description = request.Description
                };

                _dbContext.Add(todo);
                await _dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

                return _mapper.Map<TodoViewModel>(todo);
            }
        }

        public class Validator : AbstractValidator<TodoCreateCommand>
        {
            public Validator()
            {
                RuleFor(p => p.Name).NotEmpty();
            }
        }
    }
}
